package com.wenjiang.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wenjiang.common.constat.RedisKey;
import com.wenjiang.entity.MallGood;
import com.wenjiang.entity.MallSecKillGood;
import com.wenjiang.service.MallGoodService;
import com.wenjiang.service.MallSecKillGoodService;
import com.wenjiang.util.RedisUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.ml.job.config.Job;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 秒杀结束 触发的任务
 */
@Component
@Data
@Slf4j
public class SecKillEndJob  extends Task {




    @Autowired
    RedisUtils redisUtils;

    @Autowired
    MallGoodService mallGoodService;

    @Autowired
    MallSecKillGoodService mallSecKillGoodService;


    @Override
    @Transactional
    public void execute(JobExecutionContext context) throws JobExecutionException {


        JobDetail jobDetail = context.getJobDetail();
        // 获取具体执行的参数
        JobDataMap jobDataMap = jobDetail.getJobDataMap();

        Long goodId = (Long)jobDataMap.get("goodId");
        log.info("秒杀结束"+goodId);
        // 把该秒杀置为结束
        UpdateWrapper<MallSecKillGood> updateWrapper =new UpdateWrapper<>();
        updateWrapper.eq("good_id", goodId);
        updateWrapper.eq("is_end", 0);
        updateWrapper.set("is_end", 1);
        mallSecKillGoodService.update(updateWrapper);


        // 判断库存 比如等于0时 置为下架
        UpdateWrapper<MallGood> updateWrapper1 =new UpdateWrapper<>();
        updateWrapper1.eq("good_id", goodId);
        MallGood mallGood = mallGoodService.getById(goodId);
        if(mallGood.getGoodCount()==0){
            updateWrapper1.set("good_status", 0);
        }else {
            updateWrapper1.set("good_status", 1);
            // 删除存放用户的key；
            redisUtils.del(RedisKey.mallSecKillUser+goodId);
            // 重新设置redis 库存 给数据库
            redisUtils.set(RedisKey.mallGoodCount+goodId, mallGood.getGoodCount());
        }
        mallGoodService.update(updateWrapper1);

    }
}
